Skip to content

Longest Subarray with Sum K ​

Longest Subarray with Sum K — GeeksforGeeks

Given an array and an integer k, find the length of the longest contiguous subarray whose elements sum to exactly k.

Approach ​

The prefix sum is calculated and stored in hashmap, with value as the index. Start from i = 0 to i = num.Length because last element's sum goes to prefixSums[nums.Length]. While calculating prefixSums, check if it exists in map, and push it if it doesn't. Find currSum - k in the map and calculate maxLength.

Remarks ​

https://www.youtube.com/watch?v=frf7qxiN2qU

Can understand only by dry run

(I think better way is to understand Longest Subarray with Sum = 0 and then generalizing that).